package com.briup.sxau.service.impl;

import com.briup.sxau.bean.Student;
import com.briup.sxau.dao.IStudentRepository;
import com.briup.sxau.service.IStudentService;
import com.briup.sxau.util.SxauException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.Optional;

@Service
public class StudentServiceImpl implements IStudentService {
    @Autowired
    IStudentRepository studentRepository;
    @Override
    public Page<Student> findAll(int page, int pageSize) {
//        构建分页对象
        PageRequest request = PageRequest.of(page - 1, pageSize);
        Page<Student> students = studentRepository.findAll(request);
        return students;
    }

    @Override
    //学生名字不能相同，若相同不能插入
    public void save(Student student) {
//先通过名字取查询，看是否有数据
       Student obj =  studentRepository.findByName(student.getName());
//表示数据库查询结果为空 ==》名字没占用
       if (Objects.isNull(obj)) {
            studentRepository.save(student);
        }else {
           throw new SxauException("用户名重复，更换后重试");
       }
    }

    @Override
    public void deleteById(int id) {
//      参数类型正确 即使id不存在，删除业务也不受影响
        studentRepository.deleteById(id);
    }

    @Override
    public Student findById(int id) {
        Optional<Student> optional = studentRepository.findById(id);
        Student student = optional.orElse(null);
        if (Objects.isNull(student)){
            throw new SxauException("所选数据不存在");
        }else{
            return student;
        }
    }
}